import { Controller, Get, Post, Body, Patch, Param, Delete, Req, Res } from '@nestjs/common';
import { MinioService } from './minio.service';
import { CreateMinioDto } from './dto/create-minio.dto';
import { UpdateMinioDto } from './dto/update-minio.dto';
import { UseInterceptors, UploadedFiles } from '@nestjs/common';
import { AnyFilesInterceptor, FileInterceptor } from '@nestjs/platform-express';
import { storage } from './uploadStorage';
import * as fs from 'fs';
import * as crypto from 'crypto';
import { Request, Response } from 'express';
import * as path from 'path';

@Controller('/deploymentUnit')
export class MinioController {
  constructor(private readonly minioService: MinioService) {}

  @Post("/addMinIO")
  @UseInterceptors(AnyFilesInterceptor({ storage }))
  uploadAnyFiles(@UploadedFiles() files: Array<Express.Multer.File>, @Body() body, @Req() req: Request) {
    console.log(files,"files");
    console.log(body,"body");
    const decodedFilename = Buffer.from(files[0].originalname, 'latin1').toString('utf8');
    const bytes = files[0].size;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const fileContent = fs.readFileSync(files[0].path);
    const md5 = crypto.createHash('md5').update(fileContent).digest('hex');
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    const formattedSize = `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
    
    // 构建文件访问URL
    const protocol = req.protocol;
    const host = req.get('host');
    const fileUrl = `${protocol}://${host}/uploads/${files[0].filename}`;
    
    return {
      code: 200,
      message: '上传成功',
      data: {
        ...files[0],
        originalname: decodedFilename,
        url: fileUrl,
        size: formattedSize,
        md5: md5
      },
    };
  }

  @Get('/file/:filename')
  getFile(@Param('filename') filename: string, @Res() res: Response) {
    const filePath = path.join(process.cwd(), 'my-uploads', filename);
    
    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        code: 404,
        message: '文件不存在'
      });
    }

    // 设置响应头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    
    // 发送文件
    return res.sendFile(filePath);
  }
}
